package com.wakaca.design.pattern.behavioral.netty;

/**
 * 责任链模式的四个要素：
 * 1、责任处理器
 * 2、创建链，添加删除责任处理器
 * 3、上下文
 * 4、责任链终止机制
 * =================================
 * 当前类的功能：创建链，添加删除责任处理器
 * https://blog.csdn.net/wangkang19890121/article/details/106086141
 */
public class HandlerChainPipeline {

    // 初始化的时候造一个head，作为责任链的开始
    private HandlerChainContext headContext;

    // 构建链路的头节点
    public HandlerChainPipeline() {
        this.headContext = new HandlerChainContext(new AbstractHandler() {
            public void doHandler(HandlerChainContext handlerChainContext, Object arg0) {
                // 寻找下一个执行节点
                handlerChainContext.finaNextContext(arg0);
            }
        });
    }

    HandlerChainPipeline addHead(AbstractHandler handler) {
        HandlerChainContext temp = headContext;
        headContext = new HandlerChainContext(handler);
        headContext.next = temp;
        return this;
    }

    HandlerChainPipeline addLast(AbstractHandler handler) {
        HandlerChainContext context = headContext;
        while (context.next != null) {
            context = context.next;
        }
        context.next = new HandlerChainContext(handler);
        return this;
    }

    public void execute(Leave leave) {
        this.headContext.handler(leave);
    }

    public static void main(String[] args) {
        Leave leave = new Leave();
        leave.setUserName("张三");
        leave.setLeaveDays(10);
        HandlerChainPipeline handlerChainPipline = new HandlerChainPipeline()
                .addLast(new HeadAbstractHandler())
                .addLast(new LeaderAbstractHandler())
                .addLast(new DeptAbstractHandler())
                .addLast(new BossAbstractHandler());
        handlerChainPipline.execute(leave);
    }

}
